'''
Created on 19 Feb 2012

@author: gav.aiken
'''

import logging
import traceback
import sys
import re
import HTMLParser
import urllib

from google.appengine.api import urlfetch 

from game import CreateGame

headPlayerTeam = '<img class="float-right"\s*\
src="http://cdn.easf.www.easports.com/soccer/static/images/common/crest/fifa/large/\d+.png"\s*\
width="\d+" height="\d+" alt="[^"]+" title="([^"]+)" />'
headOpponentTeam = '<img class="float-left"\s*\
src="http://cdn.easf.www.easports.com/soccer/static/images/common/crest/fifa/large/\d+.png"\s*\
width="\d+" height="\d+" alt="[^"]+" title="([^"]+)" />'

headScoredRegex = '<span class="sprite float-right score-\d+ separator-left">\s*(\d+)</span>'
headConcededRegex = '<span class="sprite float-left score-\d+ separator-right">\s*(\d+)</span>'

tailResultsRegex = '<td rowspan="1" colspan="1">\s*\
<div class="float-left score-\d+-small">(\d+)</div>\s*\
<div class="float-left score-vs-small"></div>\s*\
<div class="float-left score-\d+-small">(\d+)</div>'
tailPlayerTeam = '<td class="rightBorder" rowspan="1" colspan="1">\s*\
<img class="crest" src="[^"]+" width="\d+" height="\d+" alt="[^"]+" title="([^"]+)" />'
tailOpponentTeam = '<td rowspan="1" colspan="1">\s*\
<img class="crest" src="[^"]+" width="\d+" height="\d+" alt="[^"]+" title="([^"]+)" />'

def safeScrapeGames(textId):
    try:
        return scrapeGames(textId)
    except:
        logging.info('-'*60)
        logging.info('Exception in user code')
        logging.info('-'*60)
        return -1

def openProfile(url):
    logging.info ('Opening... ' + url)
    res = urlfetch.fetch(url=url, deadline=60)
    if res.final_url is not None and res.final_url.find('player-profile') > 0:
        return res.final_url.split('/')[-1]
    else:
        return -1
    
def scrapeGames(textId):
    logging.info('Scraping games for: ' + textId)
    textIdEncoded = urllib.quote(textId)
    try:
        games = scrapeGamesAtUrl(textId, 'http://www.ea.com/soccer/profile/statistics/cem_ea_id/' + textIdEncoded)
        if len(games) == 0:
            games = scrapeGamesAtUrl(textId, 'http://www.ea.com/soccer/profile/statistics/PS3/' + textIdEncoded)
        if len(games) == 0:
            games = scrapeGamesAtUrl(textId, 'http://www.ea.com/soccer/profile/statistics/360/' + textIdEncoded)
    except Exception, err:
        logging.exception('Failed to scrape games for: %s, Exception: %s', textId, str(err))
        games = []
        
    return games
        
def scrapeGamesAtUrl(textId, profileUrl):
    try:
        intId = openProfile(profileUrl)
        if (intId < 0):
            logging.info ("Could not find Player '%s' at '%s'" % (textId, profileUrl))
            return []
        
        logging.info(textId + ' -> ' + intId)
        
        opponents = 'handle="([^"]+)"'
        
        # grab html
        matchHistoryUrl = "http://www.ea.com/soccer/mgd/match-history/" + intId
        logging.info ('Opening... ' + matchHistoryUrl)
        f = urlfetch.fetch(url=matchHistoryUrl, deadline=60)
        s = HTMLParser.HTMLParser().unescape(f.content)
        
        if (s.find("This player hasn't played any Head-to-Head matches within the last 30 days.") > 0):
            logging.info ('No games or account stats blocked - aborting')
            return []
        
        # grab opponents
        opponents = re.findall(opponents, s)[1:]
        
        # grab results
        scored = int(re.search(headScoredRegex, s).group(1))
        conceded = int(re.search(headConcededRegex, s).group(1))
        results = [(int(x),int(y)) for (x,y) in re.findall(tailResultsRegex, s)]
        results.insert(0, (scored, conceded))
        
        # grab teams
        playerTeam = re.search(headPlayerTeam, s).group(1)
        opponentTeam = re.search(headOpponentTeam, s).group(1)
        playerTeams = re.findall(tailPlayerTeam, s)
        opponentTeams = re.findall(tailOpponentTeam, s)
        
        teams = zip(playerTeams, opponentTeams)
        teams.insert(0, (playerTeam, opponentTeam))
        
        matchHistory = zip(teams, results, opponents)
        
        games = []
        for match in matchHistory:            
            game = CreateGame(playerId=textId, playerTeam=match[0][0],  playerScore=match[1][0], 
                        opponentId=match[2], opponentTeam=match[0][1], opponentScore=match[1][1])
            games.append(game)
            
        return games

    except Exception, err:
        logging.exception('Failed to scrape games at Url: %s, Exception: %s', profileUrl, str(err))
        return[]

if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')
    
    games = safeScrapeGames(sys.argv[1])
    if games < 0:
        print 'Could not retrieve games for ' + sys.argv[1]
        sys.exit(games)
        
    print 'Last 20 games'
    won = 0
    drew = 0
    lost = 0
    for game in games:            
        if game.result == 'W':
            won += 1
        elif game.result == 'D':
            drew += 1
        elif game.result == 'L':
            lost += 1
        print game
    print    
    print 'Record: %d-%d-%d' % (won, drew, lost)